//
//  DHProductDetail_HeadCell.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/6/9.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHProductDetail_HeadCell.h"
#import "DHS2_ProductInfoController.h"
#import "DHS2_BrandViewController.h"

@interface DHProductDetail_HeadCell()

@property (strong, nonatomic) NSDictionary *productDic;
@property (weak, nonatomic) IBOutlet UIScrollView *scorllView;

@property (weak, nonatomic) IBOutlet UILabel *shouLeftLabel;
@property (weak, nonatomic) IBOutlet UILabel *shouRightLabel;
@property (weak, nonatomic) IBOutlet UILabel *zuPriceLabel;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UILabel *disLabel;
@property (weak, nonatomic) IBOutlet UILabel *likeLabel;
@property (weak, nonatomic) IBOutlet UIScrollView *sizeScrollView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewWidthLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leftLabelWidthLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *rightLabelWidthLayout;
@property (weak, nonatomic) IBOutlet UIButton *dingyueButton;
@property (weak, nonatomic) IBOutlet UIButton *buyButton;

@property (strong, nonatomic) NSDictionary *selectedSize;
@property (strong, nonatomic) NSMutableArray *sizesArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *buyButtonWidthLayout;

@property (weak, nonatomic) IBOutlet UIButton *niceButton;

@property (weak, nonatomic) IBOutlet UIButton *yellowLabel;
@property (weak, nonatomic) IBOutlet UILabel *shou_xiexian_Label;
@property (weak, nonatomic) IBOutlet UIView *shou_hengxian_View;

@property (assign, nonatomic) BOOL isLiked;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *scrollViewHeightLayout;

@property (assign, nonatomic) int likeCount;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *disLabelWidthLayout;
@property (strong, nonatomic) UIImageView *disArrowImgView;

@end

@implementation DHProductDetail_HeadCell

- (void)awakeFromNib {
    [super awakeFromNib];
    
    self.scrollViewHeightLayout.constant = kScreenWidth * 1.29;
    
    [self.niceButton bk_addEventHandler:^(id sender) {
        NSDictionary *params = @{@"product_id":[self.productDic objectForKey:@"_id"],
                                 @"collect":[NSNumber numberWithBool:!self.isLiked]
                                 };
        if (self.isLiked) {
            [self.niceButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
            self.likeCount -= 1;
            self.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
            [[DHNetAPIClient shareDHNetAPIClient] request_product_collectWithParams:params andBlock:^(id data, NSError *error) {
                self.isLiked = !self.isLiked;
            }];
        }else{
            [self.niceButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
            self.likeCount += 1;
            self.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
            [[DHNetAPIClient shareDHNetAPIClient] request_product_collectWithParams:params andBlock:^(id data, NSError *error) {
                self.isLiked = !self.isLiked;
            }];
        }
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.disArrowImgView = [[UIImageView alloc] initWithFrame:CGRectMake(self.disLabel.width - 20, 0, 20, self.disLabel.height)];
    self.disArrowImgView.image = [UIImage imageNamed:@"arrow_right"];
    self.disArrowImgView.contentMode = UIViewContentModeCenter;
    [self.disLabel addSubview:self.disArrowImgView];
    
    [self.disLabel bk_whenTapped:^{
        DHS2_BrandViewController *vc = [[DHS2_BrandViewController alloc] initWithBrandID:[[self.productDic objectForKey:@"brand"] objectForKey:@"_id"]];
        [self.viewController.navigationController pushViewController:vc animated:YES];
    }];
}

- (NSMutableArray *)sizesArray{
    if (!_sizesArray) {
        _sizesArray = [NSMutableArray array];
    }
    return _sizesArray;
}

- (IBAction)buyAction:(id)sender {
    if (self.selectedSize) {
        [[DHNetAPIClient shareDHNetAPIClient] request_cart_addWithParams:@{@"type":@"购买",@"object":[self.selectedSize objectForKey:@"_id"],@"count":@"1"} andBlock:^(id data, NSError *error) {
            if (data) {
                [NSObject showHudTipStr:@"添加成功"];
                [self routerEventWithName:@"refresh_cart_number" userInfo:nil];
            }
        }];
    }else{
        [NSObject showHudTipStr:@"请选择一个尺寸"];
    }
}

- (IBAction)infoAction:(id)sender {
    DHS2_ProductInfoController *vc = [[DHS2_ProductInfoController alloc] initWithProduct:self.productDic];
    [self.viewController.navigationController pushViewController:vc animated:YES];
}

- (IBAction)subscribeAction:(id)sender {
    if (self.selectedSize) {
        [[DHNetAPIClient shareDHNetAPIClient] request_cart_addWithParams:@{@"type":@"订阅",@"object":[self.selectedSize objectForKey:@"_id"],@"count":@"1"} andBlock:^(id data, NSError *error) {
            if (data) {
                [NSObject showHudTipStr:@"添加成功"];
                [self routerEventWithName:@"refresh_cart_number" userInfo:nil];
            }
        }];
    }else{
        [NSObject showHudTipStr:@"请选择一个尺寸"];
    }
}

- (void)updateCell:(NSDictionary *)dic sizes:(NSArray *)sizesArray{
    self.productDic = dic;
    [self.sizesArray removeAllObjects];
    [self.sizesArray addObjectsFromArray:sizesArray];
    
    if (![[self.productDic objectForKey:@"can_be_purchased"] boolValue]) {
        self.buyButton.hidden = YES;
        self.buyButtonWidthLayout.constant = 0;
    }
    if (![[self.productDic objectForKey:@"can_be_leased"] boolValue]) {
        self.dingyueButton.hidden = YES;
    }
    
    self.shouLeftLabel.text = [NSString stringWithFormat:@"￥%@",[self.productDic objectForKey:@"discount_price"]];
    self.leftLabelWidthLayout.constant = [self.shouLeftLabel.text widthForFont:self.shouLeftLabel.font] + 5;
    self.shouRightLabel.text = [NSString stringWithFormat:@"￥%@",[self.productDic objectForKey:@"sales_price"]];
    self.rightLabelWidthLayout.constant = [self.shouRightLabel.text widthForFont:self.shouRightLabel.font] + 5;
    self.lineViewWidthLayout.constant = self.rightLabelWidthLayout.constant;
    self.zuPriceLabel.text = [NSString stringWithFormat:@"￥%@",[self.productDic objectForKey:@"lease_price"]];
    if ([[self.productDic objectForKey:@"lease_price"] integerValue] == 0) {
        self.yellowLabel.hidden = YES;
    }else{
        self.yellowLabel.hidden = NO;
    }
    
    CGFloat sales_price= [[self.productDic objectForKey:@"sales_price"] floatValue];
    CGFloat discount_price = [[self.productDic objectForKey:@"discount_price"] floatValue];
    if (sales_price == discount_price) {
        self.shouRightLabel.hidden = YES;
        self.shou_xiexian_Label.hidden = YES;
        self.shou_hengxian_View.hidden = YES;
    }else{
        self.shouRightLabel.hidden = NO;
        self.shou_xiexian_Label.hidden = NO;
        self.shou_hengxian_View.hidden = NO;
    }
    
    // coverScrollView
    [self.scorllView removeAllSubviews];
    NSArray *snapshots = [self.productDic objectForKey:@"snapshots"];
    self.scorllView.contentSize = CGSizeMake(self.scorllView.width * snapshots.count, self.scorllView.height);
    [snapshots enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(idx * self.scorllView.width, 0, self.scorllView.width, self.scorllView.height)];
        imgView.contentMode = UIViewContentModeScaleToFill;
        imgView.layer.masksToBounds = YES;
        [imgView dh_setImageURLString:obj];
        [self.scorllView addSubview:imgView];
    }];
    self.nameLabel.text = [self.productDic objectForKey:@"name"];
    
    self.disLabel.text = [[self.productDic objectForKey:@"brand"] objectForKey:@"name"];
    CGFloat w = [self.disLabel.text widthForFont:self.disLabel.font];
    self.disLabelWidthLayout.constant = w + 40;
    self.disArrowImgView.left = self.disLabelWidthLayout.constant - 20;
    
    if ([self.productDic objectForKey:@"collected"]) {
        self.likeCount = [[self.productDic objectForKey:@"collected"] intValue];
    }else{
        self.likeCount = 0;
    }
    self.likeLabel.text = [NSString stringWithFormat:@"%d个赞",self.likeCount];
    
    if ([[self.productDic objectForKey:@"collected"] boolValue]) {
        [self.niceButton setImage:[UIImage imageNamed:@"product_like"] forState:UIControlStateNormal];
        self.isLiked = YES;
    }else{
        [self.niceButton setImage:[UIImage imageNamed:@"product_unlike"] forState:UIControlStateNormal];
        self.isLiked = NO;
    }
    
    if (self.sizesArray.count > 0) {
        self.dingyueButton.backgroundColor = [UIColor colorWithHexString:@"#F7BB18"];
        self.buyButton.backgroundColor = [UIColor colorWithHexString:@"#5F657B"];
        self.dingyueButton.userInteractionEnabled = YES;
        self.buyButton.userInteractionEnabled = YES;
        
        [self.sizeScrollView removeAllSubviews];
        CGFloat spaceX = 3;
        CGFloat W = self.sizeScrollView.height - 6;
        [self.sizesArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            UIButton *itemButton = [[UIButton alloc] initWithFrame:CGRectMake((spaceX + W) * idx + spaceX, 3, W, W)];
            [itemButton setTitle:[obj objectForKey:@"size"] forState:UIControlStateNormal];
            [itemButton setTitleColor:[UIColor colorWithHexString:@"#4A4A4A"] forState:UIControlStateNormal];
            itemButton.titleLabel.font = [UIFont boldSystemFontOfSize:16];
            itemButton.layer.cornerRadius = W / 2;
            itemButton.tag = idx;
            [itemButton addTarget:self action:@selector(clickAction:) forControlEvents:UIControlEventTouchUpInside];
            if ([[obj objectForKey:@"inventory"] integerValue] - [[obj objectForKey:@"locked"] integerValue] <= 0) {
                itemButton.userInteractionEnabled = NO;
                [itemButton setTitleColor:RGB(200, 200, 200) forState:UIControlStateNormal];
            }
            itemButton.titleLabel.adjustsFontSizeToFitWidth = YES;
            [self.sizeScrollView addSubview:itemButton];
            
            self.sizeScrollView.contentSize = CGSizeMake(W * self.sizesArray.count + spaceX * (sizesArray.count + 1), 50);
        }];
    }else{
        self.dingyueButton.backgroundColor = [UIColor colorWithHexString:@"#BABABA"];
        self.buyButton.backgroundColor = [UIColor colorWithHexString:@"#BABABA"];
        self.dingyueButton.userInteractionEnabled = NO;
        self.buyButton.userInteractionEnabled = NO;
    }
}

- (void)clickAction:(UIButton *)sender{
    sender.selected = !sender.selected;
    if (sender.isSelected) {
        UIImageView *bgImageView = [[UIImageView alloc] initWithFrame:CGRectMake(3, 3, sender.height - 6, sender.height - 6)];
        bgImageView.tag = 1000;
        bgImageView.image = [UIImage imageWithColor:[UIColor colorWithHexString:@"#5F657B"]];
        bgImageView.layer.cornerRadius = (sender.height - 6)/2;
        bgImageView.layer.masksToBounds = YES;
        bgImageView.alpha = 0;
        [sender insertSubview:bgImageView atIndex:0];
        [sender setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [UIView animateWithDuration:0.2 animations:^{
            bgImageView.alpha = 1.0;
        }];
    }else{
        for (UIView *view in sender.subviews) {
            if (view.tag == 1000) {
                [view removeFromSuperview];
            }
        }
        [sender setTitleColor:[UIColor colorWithHexString:@"#4A4A4A"] forState:UIControlStateNormal];
    }
    
    for (UIButton *item in self.sizeScrollView.subviews) {
        if (item.tag != sender.tag) {
            item.selected = NO;
            for (UIView *view in item.subviews) {
                if (view.tag == 1000) {
                    [view removeFromSuperview];
                }
            }
            if (item.userInteractionEnabled) {
                [item setTitleColor:[UIColor colorWithHexString:@"#4A4A4A"] forState:UIControlStateNormal];
            }
        }
    }
    
    if (sender.isSelected) {
        self.selectedSize = [self.sizesArray objectAtIndex:sender.tag];
    }else{
        self.selectedSize = nil;
    }
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
